package com.jinyu.jyly.ui.mall;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.loader.ImageLoader;
import com.jinyu.jyly.R;
import com.jinyu.jyly.base.BaseFragment;
import com.jinyu.jyly.bean.AllInfoBean;
import com.jinyu.jyly.bean.GoodsTypeInfo;
import com.jinyu.jyly.event.SeachNoticeEvent;
import com.jinyu.jyly.utils.AES;
import com.jinyu.jyly.utils.DateTimeUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 商城
 */
public class MallFragment extends BaseFragment<MallPresenter> implements ViewPager.OnPageChangeListener, MallContract.View {
    @BindView(R.id.fake_status_bar)
    View fakeStatusBar;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.iv_word_one_img)
    ImageView ivWordOneImg;
    @BindView(R.id.tv_word_one_state)
    TextView tvWordOneState;
    @BindView(R.id.tv_word_one_time)
    TextView tvWordOneTime;
    @BindView(R.id.ll_one)
    LinearLayout llOne;
    @BindView(R.id.iv_word_two_img)
    ImageView ivWordTwoImg;
    @BindView(R.id.tv_word_two_state)
    TextView tvWordTwoState;
    @BindView(R.id.tv_word_two_time)
    TextView tvWordTwoTime;
    @BindView(R.id.ll_two)
    LinearLayout llTwo;
    @BindView(R.id.iv_word_three_img)
    ImageView ivWordThreeImg;
    @BindView(R.id.tv_word_three_state)
    TextView tvWordThreeState;
    @BindView(R.id.tv_word_three_time)
    TextView tvWordThreeTime;
    @BindView(R.id.ll_three)
    LinearLayout llThree;
    @BindView(R.id.viewpager)
    ViewPager viewpager;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;


    private MallPresenter presenter;
    private int oneId;
    private int twoId;
    private int threeId;

    @Override
    protected View initView(ViewGroup container) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.fragment_mall01, container, false);
        return view;
    }

    @Override
    protected void loadData() {
        initViewpager();
        initBanner();
        initData();


        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                EventBus.getDefault().post(new SeachNoticeEvent("0"));
                initBanner();
                initData();
            }
        });
    }

    private void initData() {
        //获取商品分类
        mPresenter.goodTypes();
        mPresenter.getTimes();
    }


    private void initBanner() {
        try {
            //获取banner
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("cid", 40); //37
            String param = AES.encryptToHexString(jsonObject.toString());
            mPresenter.onSiteAd(param);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @Override
    public MallPresenter getPresenter() {
        if (presenter == null) {
            presenter = new MallPresenter(getActivity(), this);
        }
        return presenter;
    }

    private void initViewpager() {
        MyPagerAdapter myPagerAdapter = new MyPagerAdapter(getChildFragmentManager());
        viewpager.setOffscreenPageLimit(3);
        viewpager.setAdapter(myPagerAdapter);
        viewpager.addOnPageChangeListener(this);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        switch (position) {
            case 0:
                viewpager.setCurrentItem(0);
                setOneState();
                break;
            case 1:
                viewpager.setCurrentItem(1);
                setTwoSate();
                break;
            case 2:
                viewpager.setCurrentItem(2);
                setThreeState();
                break;
            default:
                break;
        }
    }


    private void setThreeState() {
        ivWordOneImg.setImageResource(R.mipmap.icon_word_one_normal);
        ivWordTwoImg.setImageResource(R.mipmap.icon_word_two_normal);
        ivWordThreeImg.setImageResource(R.mipmap.icon_word_three_press);

//        tvWordOneState.setBackground(getResources().getDrawable(R.drawable.shape_gray_no_kaiguan));
//        tvWordTwoState.setBackground(getResources().getDrawable(R.drawable.shape_gray_no_kaiguan));
//        tvWordThreeState.setBackground(getResources().getDrawable(R.drawable.shape_blue_kaiguan));

        tvWordOneTime.setBackground(getResources().getDrawable(R.mipmap.icon_shop_time_normal));
        tvWordTwoTime.setBackground(getResources().getDrawable(R.mipmap.icon_shop_time_normal));
        tvWordThreeTime.setBackground(getResources().getDrawable(R.mipmap.icon_shop_time_press));
    }

    private void setTwoSate() {
        ivWordOneImg.setImageResource(R.mipmap.icon_word_one_normal);
        ivWordTwoImg.setImageResource(R.mipmap.icon_word_two_press);
        ivWordThreeImg.setImageResource(R.mipmap.icon_word_three_normal);

//        tvWordOneState.setBackground(getResources().getDrawable(R.drawable.shape_gray_no_kaiguan));
//        tvWordTwoState.setBackground(getResources().getDrawable(R.drawable.shape_blue_kaiguan));
//        tvWordThreeState.setBackground(getResources().getDrawable(R.drawable.shape_gray_no_kaiguan));

        tvWordOneTime.setBackground(getResources().getDrawable(R.mipmap.icon_shop_time_normal));
        tvWordTwoTime.setBackground(getResources().getDrawable(R.mipmap.icon_shop_time_press));
        tvWordThreeTime.setBackground(getResources().getDrawable(R.mipmap.icon_shop_time_normal));
    }

    private void setOneState() {
        ivWordOneImg.setImageResource(R.mipmap.icon_word_one_press);
        ivWordTwoImg.setImageResource(R.mipmap.icon_word_two_normal);
        ivWordThreeImg.setImageResource(R.mipmap.icon_word_three_normal);

//        tvWordOneState.setBackground(getResources().getDrawable(R.drawable.shape_blue_kaiguan));
//        tvWordTwoState.setBackground(getResources().getDrawable(R.drawable.shape_gray_no_kaiguan));
//        tvWordThreeState.setBackground(getResources().getDrawable(R.drawable.shape_gray_no_kaiguan));

        tvWordOneTime.setBackground(getResources().getDrawable(R.mipmap.icon_shop_time_press));
        tvWordTwoTime.setBackground(getResources().getDrawable(R.mipmap.icon_shop_time_normal));
        tvWordThreeTime.setBackground(getResources().getDrawable(R.mipmap.icon_shop_time_normal));
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }


    @OnClick({R.id.ll_one, R.id.ll_two, R.id.ll_three})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_one:
                setOneState();
                viewpager.setCurrentItem(0);
                break;
            case R.id.ll_two:
                setTwoSate();
                viewpager.setCurrentItem(1);
                break;
            case R.id.ll_three:
                setThreeState();
                viewpager.setCurrentItem(2);
                break;
        }
    }

    @Override
    public void onFailer(Throwable throwable) {
        mRefreshLayout.finishLoadMore();
        mRefreshLayout.finishRefresh();
    }

    /**
     * 获取banner
     *
     * @param info
     */
    @Override
    public void onSiteAd(AllInfoBean info) {
        mRefreshLayout.finishLoadMore();
        mRefreshLayout.finishRefresh();
        switch (info.getStatus()) {
            case 200:
                try {
                    String infodata = AES.decrypt(info.getData());
                    Gson gson = new Gson();
                    Type listType = new TypeToken<ArrayList<String>>() {
                    }.getType();
                    List<String> mList = gson.fromJson(infodata, listType);
                    setBanner(mList);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case 422:
                showToast(info.getMsg());
                break;
            default:
                break;
        }
    }

    /**
     * 获取商品分类
     *
     * @param infoBean
     */
    @Override
    public void onGoodsTypes(AllInfoBean infoBean) {
        mRefreshLayout.finishLoadMore();
        mRefreshLayout.finishRefresh();
        switch (infoBean.getStatus()) {
            case 200:
                String data = infoBean.getData();
                String result = null;
                try {
                    result = AES.decrypt(data);
                    Gson gson = new Gson();
                    Type listType = new TypeToken<ArrayList<GoodsTypeInfo>>() {
                    }.getType();
                    List<GoodsTypeInfo> mList = gson.fromJson(result, listType);
                    setGoodsCateOne(mList);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case 422:
                showToast(infoBean.getMsg());
                break;
            default:
                break;
        }
    }

    @Override
    public void onGoodList(AllInfoBean infoBean) {
        mRefreshLayout.finishLoadMore();
        mRefreshLayout.finishRefresh();
    }

    /**
     * 获取时间
     *
     * @param infoBean
     */
    @Override
    public void onGetTimes(AllInfoBean infoBean) {
        mRefreshLayout.finishLoadMore();
        mRefreshLayout.finishRefresh();
        switch (infoBean.getStatus()) {
            case 200:
                String data = infoBean.getData();
                try {
                    String result = AES.decrypt(data);
                    JSONObject jsonObject = new JSONObject(result);
                    long zao_start = jsonObject.optLong("zao_start",0l);
                    long zao_end = jsonObject.optLong("zao_end",0l);
                    long wu_start = jsonObject.optLong("wu_start",0l);
                    long wu_end = jsonObject.optLong("wu_end",0l);
                    long wan_start = jsonObject.optLong("wan_start",0l);
                    long wan_end = jsonObject.optLong("wan_end",0l);

                    long zao_start_time = jsonObject.optLong("zao_start_time",0l);
                    long zao_end_time = jsonObject.optLong("zao_end_time",0l);
                    long wu_start_time = jsonObject.optLong("wu_start_time",0l);
                    long wu_end_time = jsonObject.optLong("wu_end_time",0l);
                    long wan_start_time = jsonObject.optLong("wan_start_time",0l);
                    long wan_end_time = jsonObject.optLong("wan_end_time",0l);

                    tvWordOneTime.setText(DateTimeUtils.getStrTime(zao_start_time+"")+"-"+ DateTimeUtils.getStrTime(zao_end_time+""));
                    tvWordTwoTime.setText(DateTimeUtils.getStrTime(wu_start_time+"")+"-"+DateTimeUtils.getStrTime(wu_end_time+""));
                    tvWordThreeTime.setText(DateTimeUtils.getStrTime(wan_start_time+"")+"-"+DateTimeUtils.getStrTime(wan_end_time+""));

                    if (zao_start == 0) {
                        tvWordOneState.setText("未开馆");
                        tvWordOneState.setBackground(getResources().getDrawable(R.drawable.shape_gray_no_kaiguan));
                        tvWordOneState.setTextColor(getResources().getColor(R.color.gray05));
                    } else {
                        //开启
                        tvWordOneState.setText("已开馆");
                        tvWordOneState.setBackground(getResources().getDrawable(R.drawable.shape_blue_kaiguan));
                        tvWordOneState.setTextColor(getResources().getColor(R.color.orange02));
                    }

                    if (wu_start == 0) {
                        tvWordTwoState.setText("未开馆");
                        tvWordTwoState.setBackground(getResources().getDrawable(R.drawable.shape_gray_no_kaiguan));
                        tvWordTwoState.setTextColor(getResources().getColor(R.color.gray05));
                    } else {
                        //开启
                        tvWordTwoState.setText("已开馆");
                        tvWordTwoState.setBackground(getResources().getDrawable(R.drawable.shape_blue_kaiguan));
                        tvWordTwoState.setTextColor(getResources().getColor(R.color.orange02));
                    }

                    if (wan_start == 0) {
                        tvWordThreeState.setText("未开馆");
                        tvWordThreeState.setBackground(getResources().getDrawable(R.drawable.shape_gray_no_kaiguan));
                        tvWordThreeState.setTextColor(getResources().getColor(R.color.gray05));
                    } else {
                        //开启
                        tvWordThreeState.setText("已开馆");
                        tvWordThreeState.setBackground(getResources().getDrawable(R.drawable.shape_blue_kaiguan));
                        tvWordThreeState.setTextColor(getResources().getColor(R.color.orange02));
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case 422:
                showToast(infoBean.getMsg());
                break;
            default:
                break;
        }
    }

    @Override
    public void onPageGoodList(AllInfoBean infoBean) {

    }

    private void setGoodsCateOne(List<GoodsTypeInfo> mList) {
        if (mList != null && mList.size() != 0) {
            GoodsTypeInfo goodsTypeInfo = mList.get(0);
            if (goodsTypeInfo != null) {
                oneId = goodsTypeInfo.getId();
            }
        }

        if (mList != null && mList.size() > 1) {
            GoodsTypeInfo goodsTypeInfo = mList.get(1);
            twoId = goodsTypeInfo.getId();
        }

        if (mList != null && mList.size() > 2) {
            GoodsTypeInfo goodsTypeInfo2 = mList.get(2);
            threeId = goodsTypeInfo2.getId();
        }
    }

    /**
     * 设置banner
     *
     * @param mList
     */
    private void setBanner(List<String> mList) {
        //设置内置样式，共有六种可以点入方法内逐一体验使用。
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR); //CIRCLE_INDICATOR
        //设置图片加载器，图片加载器在下方
        banner.setImageLoader(new MyLoader());
        //设置图片网址或地址的集合
        banner.setImages(mList);
        //设置轮播图的标题集合
        banner.setBannerTitles(mList);
        //设置轮播的动画效果，内含多种特效，可点入方法内查找后内逐一体验
        banner.setBannerAnimation(Transformer.Accordion);//Default  //Accordion
        //设置轮播间隔时间
        banner.setDelayTime(3000);
        //设置是否为自动轮播，默认是“是”。
        banner.isAutoPlay(true);
        //设置指示器的位置，小点点，左中右。
        banner.setIndicatorGravity(BannerConfig.CENTER) //CENTER
                //以上内容都可写成链式布局，这是轮播图的监听。比较重要。方法在下面。
//                          .setOnBannerListener(this)
                //必须最后调用的方法，启动轮播图。
                .start();
    }


    //自定义的图片加载器
    private class MyLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            RequestOptions options = new RequestOptions();
            options.error(R.mipmap.space_list);
            Glide.with(context).load(path)
                    .apply(options)
                    .into(imageView);
        }
    }


    class MyPagerAdapter extends FragmentPagerAdapter {
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return "";
        }

        @Override
        public Fragment getItem(int position) {
            if (position == 0) {
                //
                return MallTabFragment.newInstance(1);
            } else if (position == 1) {
                //
                return MallTabFragment.newInstance(2);
            } else {
                return MallTabFragment.newInstance(3);
            }
        }

        @Override
        public int getCount() {
            return 3;
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


}
